package application.employee.service;

import application.employee.api.EmployeeServiceInterface;
import application.employee.model.Employee;
import application.employee.repository.EmployeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Objects;

/**
 * 雇员 业务层实现
 *
 * @author roamer
 * @version V1.0
 * @date 2019-02-24 10:21
 */
@Service
@Slf4j
public class EmployeeService implements EmployeeServiceInterface {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public Employee addEmployee(Employee employee) {
        employeeRepository.save(employee);
        log.info("Add Employee : {}", employee);
        return employee;
    }

    @Override
    public Collection<Employee> getEmployees() {
        return employeeRepository.queryAll();
    }

    @Override
    public Employee getEmployee(String id) {
        return employeeRepository.queryById(id);
    }

    @Override
    public Employee updateEmployee(String id, Employee employee) {
        Employee old = employeeRepository.queryById(id);
        if (Objects.nonNull(employee)) {
            old.setName(employee.getName());
            log.info("Update Employee : {}", employee);
            return employeeRepository.save(old);
        }
        return null;
    }

    @Override
    public Employee updateEmployeeDetail(String id, Employee employee) {
        if (Objects.nonNull(employee.getEmployeeDetail())) {
            employee.getEmployeeDetail().setId(id);
            return employeeRepository.updateEmployee(employee.getEmployeeDetail());
        }
        return null;
    }

    @Override
    public Collection<Employee> findEmployeesByName(String name) {
        return employeeRepository.queryByName(name);
    }

    @Override
    public Employee deleteEmployee(String id) {
        Employee employee = employeeRepository.queryById(id);
        if (Objects.nonNull(employee)) {
            log.info("Delete Employee : {}", employee);
            employeeRepository.delete(employee);
        }
        return employee;
    }
}
